/*
 * Copyright (c) 2018-2999 九五云信息科技有限公司 All rights reserved.
 *
 * https://www.gz-yami.com/
 *
 * 未经允许，不可做商业用途！
 *
 * 版权所有，侵权必究！
 */

package com.yami.shop.sys.multishop.security;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.yami.shop.bean.enums.PositionType;
import com.yami.shop.bean.enums.ShopStatus;
import com.yami.shop.bean.model.ShopDetail;
import com.yami.shop.common.config.Constant;
import com.yami.shop.dao.ShopDetailMapper;
import com.yami.shop.security.comment.exception.UsernameNotFoundException;
import com.yami.shop.security.comment.exception.YamiAuthFilterException;
import com.yami.shop.security.comment.model.YamiGrantedAuthority;
import com.yami.shop.security.multishop.model.YamiShopUser;
import com.yami.shop.sys.comment.dao.ShopEmployeeMapper;
import com.yami.shop.sys.comment.dao.ShopMenuMapper;
import com.yami.shop.sys.comment.model.ShopEmployee;
import com.yami.shop.sys.comment.model.ShopMenu;
import com.yami.shop.sys.comment.model.SysMenu;
import lombok.AllArgsConstructor;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Primary;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * 用户详细信息
 *
 * @author
 */
@Slf4j
@Primary
@Service
@AllArgsConstructor
public class YamiShopUserDetailsServiceImpl implements UserDetailsService {

//    private final ShopDetailMapper shopDetailMapper;

    private final ShopEmployeeMapper shopEmployeeMapper;

    private final ShopMenuMapper shopMenuMapper;

    /**
     * 用户密码登录
     *
     * @param username 用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    @SneakyThrows
    public YamiShopUser loadUserByUsername(String username) {
//        ShopDetail shopDetail = shopDetailMapper.getShopByMobile(username)
        ShopEmployee shopDetail = shopEmployeeMapper.getShopByMobileOrEmail(username);

        if (shopDetail == null) {
            // 未找到此用户信息
            throw new UsernameNotFoundException("yami.user.no.exist");
        }
        // 不是店铺超级管理员，并且是禁用状态，无法登录
        if (!Objects.equals(PositionType.ADMIN.value(), shopDetail.getType()) && Objects.equals(shopDetail.getStatus(),0)) {
            // 未找到此用户信息
            throw new YamiAuthFilterException("yami.shop.user.account.lock");
        }

        Collection<GrantedAuthority> authorities
                = getUserPermissions(shopDetail);

        YamiShopUser shopUser = new YamiShopUser();
        shopUser.setEnabled(
                !(Objects.equals(shopDetail.getShopStatus(), ShopStatus.NOTOPEN.value())
                || Objects.equals(shopDetail.getShopStatus(), ShopStatus.OFFLINE.value())));
        shopUser.setPassword(shopDetail.getPassword());
        shopUser.setUserId(shopDetail.getUserId());
        shopUser.setShopId(shopDetail.getShopId());
        shopUser.setUsername(shopDetail.getMobile());
        shopUser.setEmployeeId(shopDetail.getEmployeeId());
        shopUser.setAuthorities(authorities);
        return shopUser;
    }

    private List<GrantedAuthority> getUserPermissions(ShopEmployee shopEmployee) {
        Integer type = shopEmployee.getType();
        Long employeeId = shopEmployee.getEmployeeId();
        List<String> permsList;

        //店铺超级管理员，拥有最高权限
        if(Objects.equals(PositionType.ADMIN.value(),type)){
            List<ShopMenu> menuList = shopMenuMapper.selectList(Wrappers.emptyWrapper());
            permsList = menuList.stream().map(ShopMenu::getPerms).collect(Collectors.toList());
        }else{
            permsList = shopEmployeeMapper.queryAllPerms(employeeId);
        }


        Set<String> permsSet = permsList.stream().flatMap((perms)->{
                    if (StrUtil.isBlank(perms)) {
                        return null;
                    }
                    return Arrays.stream(perms.trim().split(StrUtil.COMMA));
                }).collect(Collectors.toSet());

        // 将权限组合成spring 需要的格式
        List<GrantedAuthority> authorities = new ArrayList<>(permsSet.size());

        for (String perms : permsSet) {
            YamiGrantedAuthority yamiGrantedAuthority = new YamiGrantedAuthority();
            yamiGrantedAuthority.setPerms(perms);
            authorities.add(yamiGrantedAuthority);
        }

        return authorities;
    }
}
